﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CAD1Controller : BuyiController
    {

        // GET: api/CAD1/5
        [HttpPost, Route("cad1")]
        public HttpResponseMessage Post(int ModelId)
        {
            Style style = GetStyleByModel(ModelId);
            if (style == null)
                return AssistFun.toJson(new { status = 201, tip = "找不到对应的数据" });
            string stylePath = GetStylePath(style);
            string modelPath = GetPCPath(style.model_name);

            List<string> name = new List<string>();
            List<string> val = new List<string>();
            try
            {
                string newmodel = modelPath + "\\" + style.style_name + ".model";
                if (!File.Exists(newmodel))
                    return AssistFun.toJson(new { status = 201, tip = "当前文件不存在" });
                string res = ReadModel(stylePath, newmodel, style.model_name, name, val);
                //成功移动文件到历史目录
                if (res != null)
                {
                    if (style.save_model == 0)
                        CopyFile0(stylePath, modelPath, style.model_name);
                    else
                        CopyFile(stylePath, modelPath, style.style_name, name, val);

                    InsertXml(stylePath + "\\" + style.style_name + ".model", res, ModelId);
                    WriteDebug("AddModelToFile", "开始移动文件到历史目录");
                    string hisPath = GetHistoryStylePath(style.style_time);
                    MoveFolder(modelPath, hisPath + "\\" + style.model_name);
                    return AssistFun.toJson(new { status = 200, tip = "成功" });
                }
                return AssistFun.toJson(new { status = 201, tip = "失败" });
            }
            catch (Exception e)
            {
                WriteDebug("AddModelToFile", e.Message);
                return AssistFun.toJson(new { status = 201, tip = "文件操作失败," + e.Message });
            }

        }
        

        private int AddModelToFile(int ModelId, XmlNode newModel, string oldModel)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(oldModel);
            XmlNode node = doc.SelectSingleNode("//modelList");
            node.AppendChild(newModel);
            doc.Save(oldModel);

            string sql = "update Model_tb set state=2 where id=@id";
            SQLCommand sc = new SQLCommand(sql, "@id", ModelId);
            int rtn = sc.ExecuteNonQuery();
            return rtn;
        }

        private void CopyFile0(string stylePath, string modelPath, string modelname)
        {
            File.Copy(modelPath + "\\" + modelname + ".prj", stylePath + "\\" + modelname + ".prj", true);
        }

        private void CopyFile(string stylePath, string modelPath, string stylename, List<string> name, List<string> val)
        {
            for (int i = 0; i < name.Count; i++)
                File.Copy(modelPath + "\\A1\\" + name[i] + ".prj", stylePath + "\\A1\\" + name[i] + "\\" + val[i] + ".prj", true);

            File.Copy(modelPath + "\\A1\\" + stylename + ".prj", stylePath + "\\A1\\" + stylename + ".prj", true);
        }


        #region
        /// <summary>
        /// 在已有款的model文件中加入一个新的款  同时新增一条样式记录
        /// </summary> 
        /// <param name="oldModel"></param>
        /// <param name="newModel"></param>
        /// <param name="modelName"></param>
        private string ReadModel(string oldModel, string newModel, string modelName, List<string> name, List<string> val)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(newModel);
                //获取name集合
                XmlNode para = doc.SelectSingleNode("//param");
                foreach (XmlNode item in para.SelectSingleNode("//part").ChildNodes)
                {
                    if (!string.IsNullOrEmpty(item.InnerText))
                        name.Add(item.InnerText);
                }
                //获取val集合以及新的model节点
                XmlNodeList nodeList = doc.GetElementsByTagName("model");

                for (int i = 0; i < nodeList.Count; i++)
                {
                    XmlNode newNode = GetNewNode(nodeList[i], val, modelName);
                    if (newNode != null)
                    {
                        return newNode.OuterXml;
                    }
                }
                WriteDebug("ReadModel", "没有找到相应的model节点");
                return null;
            }
            catch (Exception e)
            {
                WriteDebug("AddModelToFile", e.Message);
                return null;
            }
        }

        private XmlNode GetNewNode(XmlNode node, List<string> val, string modelName)
        {
            XmlNode newNode = null;
            foreach (XmlNode item in node)
            {
                if (item.Name.Equals("name") && item.InnerText.Equals(modelName))
                {
                    newNode = node;
                    foreach (XmlNode it in node.ChildNodes)
                    {
                        if (it.Name.Equals("part"))
                        {
                            foreach (XmlNode p in it.ChildNodes)
                            {
                                if (!string.IsNullOrEmpty(p.InnerText))
                                    val.Add(p.InnerText);
                            }
                            break;
                        }
                    }
                    break;
                }
            }
            return newNode;
        }

        private bool UpdateModel(int ModelId)
        {
            string sql = "update Model_tb set state=2 where id=@id";
            SQLCommand sc = new SQLCommand(sql, "@id", ModelId);
            int rtn = sc.ExecuteNonQuery();
            if (rtn == 1)
                return true;
            else
                return false;
        }

        private bool InsertXml(string oldModel, string newNode, int ModelId)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(oldModel);
            XmlDocumentFragment xmlfrag = doc.CreateDocumentFragment();
            xmlfrag.InnerXml = newNode;
            XmlNode node = doc.SelectSingleNode("//modelList");
            node.InsertBefore(xmlfrag, node.LastChild);
            doc.Save(oldModel);
            WriteDebug("ReadModel", "成功");
            return UpdateModel(ModelId);
        }
        
        #endregion
    }
}
